/**
 * Copyright 2013-2015. Chongqing CRUN Industry Information Co.,Ltd. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.goodsogood.union.auth.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

/**
 *
 */
public class StrUtils {

    private static final String DELIM_START = "${";
    private static final String DELIM_STOP = "}";

    public static String handelUrl(String url) {
        if (url == null) {
            return null;
        }
        url = url.trim();
        if ((url.equals("")) || (url.startsWith("http://"))
                || (url.startsWith("https://"))) {
            return url;
        }
        return "http://" + url.trim();
    }

    public static String[] splitAndTrim(String str, String sep, String sep2) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        if (!StringUtils.isBlank(sep2)) {
            str = StringUtils.replace(str, sep2, sep);
        }
        String[] arr = StringUtils.split(str, sep);

        int i = 0;
        for (int len = arr.length; i < len; i++) {
            arr[i] = arr[i].trim();
        }
        return arr;
    }

    public static String txt2htm(String txt) {
        if (StringUtils.isBlank(txt)) {
            return txt;
        }
        StringBuilder sb = new StringBuilder((int) (txt.length() * 1.2D));

        boolean doub = false;
        for (int i = 0; i < txt.length(); i++) {
            char c = txt.charAt(i);
            if (c == ' ') {
                if (doub) {
                    sb.append(' ');
                    doub = false;
                } else {
                    sb.append("&nbsp;");
                    doub = true;
                }
            } else {
                doub = false;
                switch (c) {
                    case '&':
                        sb.append("&amp;");
                        break;
                    case '<':
                        sb.append("&lt;");
                        break;
                    case '>':
                        sb.append("&gt;");
                        break;
                    case '"':
                        sb.append("&quot;");
                        break;
                    case '\n':
                        sb.append("<br/>");
                        break;
                    default:
                        sb.append(c);
                }
            }
        }

        return sb.toString();
    }

    public static String textCut(String s, int len, String append) {
        if (s == null) {
            return null;
        }
        int slen = s.length();
        if (slen <= len) {
            return s;
        }

        int maxCount = len * 2;
        int count = 0;
        int i = 0;
        for (; (count < maxCount) && (i < slen); i++) {
            if (s.codePointAt(i) < 256)
                count++;
            else {
                count += 2;
            }
        }
        if (i < slen) {
            if (count > maxCount) {
                i--;
            }
            if (!StringUtils.isBlank(append)) {
                if (s.codePointAt(i - 1) < 256)
                    i -= 2;
                else {
                    i--;
                }
                return s.substring(0, i) + append;
            }
            return s.substring(0, i);
        }

        return s;
    }

    public static boolean contains(String str, String search) {
        if ((StringUtils.isBlank(str)) || (StringUtils.isBlank(search))) {
            return false;
        }
        String reg = StringUtils.replace(search, "*", ".*");
        Pattern p = Pattern.compile(reg);
        return p.matcher(str).matches();
    }

    /**
     * 解析含${xx}变量并替换
     *
     * @param val
     * @param values
     * @return
     */
    public static String replaceParams(String val, Map<String, String> values) {
        int stopDelim = val.indexOf(DELIM_STOP);
        int startDelim = val.indexOf(DELIM_START);
        while (stopDelim >= 0) {
            int idx = val.indexOf(DELIM_START, startDelim + DELIM_START.length());
            if ((idx < 0) || (idx > stopDelim)) {
                break;
            } else if (idx < stopDelim) {
                startDelim = idx;
            }
        }

        if ((startDelim < 0) && (stopDelim < 0)) {
            return val;
        } else if (((startDelim < 0) || (startDelim > stopDelim)) && (stopDelim >= 0)) {
            //throw new IllegalArgumentException("stop delimiter with no start delimiter: " + val);
            return val;
        }

        String variable = val.substring(startDelim + DELIM_START.length(), stopDelim);
        String substValue = values.get(variable);
        if (substValue == null) {
            return val;
        }

        val = val.substring(0, startDelim) + substValue + val.substring(stopDelim + DELIM_STOP.length(), val.length());
        val = replaceParams(val, values);
        return val;
    }

    public static String getRandomNumber(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(10);//[0,62)
            sb.append(number);
        }
        return sb.toString();
    }

    public static String checkUrlEncode(String string) {
        if (StringUtils.isEmpty(string)) {
            return string;
        }
        if (string.startsWith("%7B")) {
            if (string.endsWith("=")) {
                string = string.substring(0, string.length() - 1);
            }
            try {
//                string = string.replaceAll("%22", "%5c%22");
                string = URLDecoder.decode(string, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return string;
            }
            return string;
        }
        return string;
    }

    public static Map<String, String> str2Map(String str) {

        // 解决urlencode的数据
        if (str.startsWith("%7B")) {
            str = checkUrlEncode(str);
        }

        final boolean multipleSlash;
        multipleSlash = str.indexOf(":") < str.indexOf("\\\\");
        if (multipleSlash) {
            str = str.replaceAll("\\\\\\\\", "~~~");
            str = str.replaceAll("\\\\", "");
        }
        JSONObject jasonObject = JSON.parseObject(str);

        jasonObject.keySet().stream().filter(StringUtils::isNotEmpty).forEach(key -> {
            if (jasonObject.get(key) != null) {
                if (multipleSlash) {
                    jasonObject.put(key, String.valueOf(jasonObject.get(key).toString().replaceAll("~~~", "\\\\")));
                } else {
                    jasonObject.put(key, String.valueOf(jasonObject.get(key)));
                }
            }
        });
        return (Map) jasonObject;
    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
//
//        String fullFileName = "/Users/dongguochao/git/CarCare_API_v2/carcare-app/src/main/java/cn/dogchao/carcare/util/channel.json";
//
//        File file = new File(fullFileName);
//        Scanner scanner = null;
//        StringBuilder buffer = new StringBuilder();
//        try {
//            scanner = new Scanner(file, "utf-8");
//            while (scanner.hasNextLine()) {
//                buffer.append(scanner.nextLine());
//            }
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } finally {
//            if (scanner != null) {
//                scanner.close();
//            }
//        }
//        JSONArray manage = JSON.parseArray(buffer.toString());
//            for (int i = 0; i < manage.size(); i++) {
//            JSONObject obj = manage.getJSONObject(i);
//            StringBuilder sb = new StringBuilder("insert into authority_web(id, parent_id, module_id, `action`, title) values(" + obj.getIntValue("id") + "," + obj.getIntValue("parentId") + ",'" + obj.getString("moduleId") + "','" + obj.getString("action") + "','" + obj.getString("title") + "');");
//            System.out.println(sb.toString());
//            if(obj.containsKey("data")){
//                JSONArray subArary = obj.getJSONArray("data");
//                for (int j = 0; j < subArary.size(); j++) {
//                    JSONObject obj2 = subArary.getJSONObject(j);
//                    StringBuilder sb2 = new StringBuilder("insert into authority_web(id, parent_id, module_id, `action`, title) values(" + obj2.getIntValue("id") + "," + obj2.getIntValue("parentId") + ",'" + obj2.getString("moduleId") + "','" + obj2.getString("action") + "','" + obj2.getString("title") + "');");
//                    System.out.println(sb2.toString());
//                }
//            }
//        }
//http://carcare.img-cn-qingdao.aliyuncs.com/1472524775559.jpeg
//        http://carcare.img-cn-qingdao.aliyuncs.com/1472524854468.jpeg
//        http://carcare.img-cn-qingdao.aliyuncs.com/1472524864375.jpeg
//        http://carcare.img-cn-qingdao.aliyuncs.com/1472524870505.jpeg
//        System.out.println(new BASE64Encoder().encode(com.github.kevinsawicki.http.HttpRequest.get("http://carcare.img-cn-qingdao.aliyuncs.com/1472524775559.jpeg").bytes()));
//        System.out.println(new BASE64Encoder().encode(com.github.kevinsawicki.http.HttpRequest.get("http://carcare.img-cn-qingdao.aliyuncs.com/1472524854468.jpeg").bytes()));
//        System.out.println(new BASE64Encoder().encode(com.github.kevinsawicki.http.HttpRequest.get("http://carcare.img-cn-qingdao.aliyuncs.com/1472524864375.jpeg").bytes()));
//        System.out.println(new BASE64Encoder().encode(com.github.kevinsawicki.http.HttpRequest.get("http://carcare.img-cn-qingdao.aliyuncs.com/1472524870505.jpeg").bytes()));
//        System.out.println(new Md5PwdEncoder().encodePassword("Cheneibao123", "15000000002"));
//        System.out.println(new Md5PwdEncoder().encodePassword("Cheneibao123", "15000000003"));
//        System.out.println(new Md5PwdEncoder().encodePassword("Cheneibao123", "cadmin"));
//        String response = com.github.kevinsawicki.http.HttpRequest.get("http://114.215.137.173:8086/Service1.asmx/GetVehicleLastInfo?token=aaaaaaaaaaaaaaaaaaaa&cph=14140837851").body();
//        System.out.println(response.substring(response.indexOf("&lt;Status&gt;") + 14, response.indexOf("&lt;/Status&gt;")));
//        System.out.println(response.substring(response.indexOf("&lt;Direction&gt;") + 17, response.indexOf("&lt;/Direction&gt;")));
//        seract instance = new Tesseract();
//        instance.setDatapath(new File("/usr/local/Cellar/tesseract/3.04.01_2/share/tessdata").getPath());
//        instance.setLanguage("chi_sim");
//        File imageFile = new File("/Users/dongguochao/Downloads", "lic.jpg");
//        String result = null;
//        try {
//            result = instance.doOCR(imageFile);
//            System.out.println(result);
//        } catch (TesseractException e) {
//            e.printStackTrace();
//        }

//        double a = 50*24;  // 时间总共卖50*24小时
//        double b = 0.3; // 第一天只剩下70%
//        try {
//            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-01");
//            double x = Math.abs(System.currentTimeMillis()-startDate.getTime()) / 3600000;
//            System.out.println(String.valueOf((int)(100*(1 - FastMath.sqrt(1 - FastMath.pow(x/a, 2)) * b))));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }

    }
}
